// user模块
// 引入封装的axios方法
import { api_users_checkLogin, api_users_info } from '@/api/user'



const state = {
    token: localStorage.getItem('token'),
    role: localStorage.getItem('role'),
    userInfo: {},

}

const getters = {}
const mutations = {
    SET_TOKEN(state, data) {
        state.token = data
        // 将token数据同时存入本地
        localStorage.setItem('token', data)
    },
    SET_ROLE(state, data) {
        state.role = data
        // 将数据同时存入本地
        localStorage.setItem('role', data)

    },
    SET_USERINFO(state, data) {
        state.userInfo = data
    },
    // 清空vuex 本地存储
    CLEAR(state) {
        // 清空vuex
        state.userInfo = {},
            state.token = '',
            state.role = ''
        // 清空本地存储
        localStorage.clear()
    }
}
const actions = {
    // 发送登录请求
    A_user({ commit }, data) {
        return new Promise(async resolve => {
            const res = await api_users_checkLogin(data)
            let { code, token, role } = res.data
            if (code === 0) {
                commit('SET_TOKEN', 'Bearer ' + token)
                commit('SET_ROLE', role)
                resolve()
            }

        })
    },
    // 获取用户信息
    A_userInfo({ commit }) {
        return new Promise((resolve, reject) => {
            api_users_info().then(res => {
                commit('SET_USERINFO', res.data)
                resolve()
            }).catch(err => {
                reject(err)
            })
        })
    },
    // 
    A_command({ commit }) {
        return new Promise(async resolve => {
            commit('CLEAR')
            resolve()
        })
    }
}


// 导出
export default {
    // 命名空间
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}